package com.foreknow.web;


import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.foreknow.entity.User;
import com.foreknow.service.UserService;
import com.foreknow.utils.Constance;
import com.foreknow.utils.TokenUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;


@Api
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;


    @ApiOperation("登录")
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public String login(@RequestBody Map<String, Object> para) throws JsonProcessingException, Exception {
        String username = (String) para.get("username");
        String password = (String) para.get("password");
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        String token = TokenUtil.sign(user);
        user.setToken(token);

        HashMap<String, Object> hs = new HashMap<>();
//    hs.put("token",token);
        hs.put("data", user);
        if (userService.queryByPassword(user) != null) {
            hs.put("meta", new Constance("msg", 200));
        } else {
            hs.put("meta", new Constance("msg", 500));

        }


        ObjectMapper objectMapper = new ObjectMapper();
        return objectMapper.writeValueAsString(hs);
    }


    @RequestMapping(value = "queryUserbyDeptAndRegistle")
    public String queryUserbyDeptAndRegistle(@RequestBody Map<String, Object> para) throws Exception {

        Integer pageSize = (Integer) para.get("pageSize");
        Integer currentPage = (Integer) para.get("currentPage");

        Integer deptid = (Integer) para.get("deptId");
        Integer registleId = (Integer) para.get("registleId");

        Integer count = userService.countOfDeptAndRegistle(deptid, registleId);

        List<User> list = userService.queryUserbyDeptAndRegistle(deptid, registleId, pageSize, currentPage);

        HashMap<String, Object> map = new HashMap<>();

        map.put("count", count);
        map.put("data", list);
        map.put("meta", new Constance("msg", 200));

        ObjectMapper objectMapper = new ObjectMapper();
        return objectMapper.writeValueAsString(map);

    }


    @RequestMapping(value = "/test", method = RequestMethod.POST)
    @ResponseBody
    public String test(@RequestBody Map<String, Object> para) throws JsonProcessingException {


        HashMap<String, Object> hs = new HashMap<>();

        hs.put("data", "data");
        ObjectMapper objectMapper = new ObjectMapper();
        return objectMapper.writeValueAsString(hs);
    }
}
